const { Sequelize, Model, DataTypes } = require('sequelize')
const config = require(__dirname + '/config/config.json')
const sequelize = new Sequelize(config)

const Theme = sequelize.define(
  'Theme',
  {
    _id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    id: {
      type: DataTypes.STRING,
      unique: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  },
  {
    tableName: 'i_themes',
    freezeTableName: true,
    timestamps: true,
    indexes: [
      {
        name: 'idx_id_name',
        fields: ['_id', 'id', 'name']
      }
    ]
  }
)

const Factor = sequelize.define(
  'Factor',
  {
    _id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    id: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false
    }
  },
  {
    tableName: 'i_factors',
    freezeTableName: true,
    timestamps: true,
    indexes: [
      {
        name: 'idx_id_name',
        fields: ['_id', 'id', 'name']
      }
    ]
  }
)

const ThemeFactorRef = sequelize.define(
  'ThemeFactorRef',
  {
    _id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    description: {
      type: DataTypes.STRING,
      allowNull: true
    },
    theme_id: {
      type: DataTypes.STRING,
      references: {
        model: Theme,
        key: 'id'
      }
    },
    factor_id: {
      type: DataTypes.STRING,
      references: {
        model: Factor,
        key: 'id'
      }
    }
  },
  {
    tableName: 'i_theme_factor_ref',
    freezeTableName: true,
    timestamps: true,
    indexes: [
      {
        name: 'idx_id_name',
        fields: ['_id']
      }
    ]
  }
)

// sequelize.sync({ alter: true })

module.exports = sequelize
